﻿package com.yang.service;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.Toast;

import com.yang.handle.PhotoHandler;
import com.yang.testservice.MainActivity;
import com.yang.testservice.R;

public class LocalService extends Service {

	private AlarmManager am = null;
	private Camera camera;
	private static final int INTERVAL = 1000 * 60 * 1;// 24h
	
	private final IBinder mBinder = new LocalBinder();
	private NotificationManager mNM;
	File file;
	SimpleDateFormat dateFormat;

	private int NOTIFICATION = R.string.local_service_started;

	/**
	 * Class for clients to access. Because we know this service always runs in
	 * the same process as its clients, we don't need to deal with IPC.
	 */
	public class LocalBinder extends Binder {
		public LocalService getService() {
			return LocalService.this;
		}
	}
	
	@Override
	public void onCreate() {
		mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		showNotification();
		
		file = getDir();
		dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
		writeTxtToFile("onCreate()==第一次创建服务");
		
	}
	
	public void writeTxtToFile(String strcontent) {	   
	
	    // 每次写入时，都换行写
		
        String date = dateFormat.format(new Date());
	    String strContent = strcontent + "====" + date + "\r\n";
	    try {
	       
	        if (!file.exists()) {
	            file.getParentFile().mkdirs();
	            file.createNewFile();
	        }
	        RandomAccessFile raf = new RandomAccessFile(file, "rwd");
	        raf.seek(file.length());
	        raf.write(strContent.getBytes());
	        raf.close();
	    } catch (Exception e) {
	        Log.e("TestFile", "Error on write File:" + e);
	    }
	}

	private void init() {
			am = (AlarmManager) getSystemService(ALARM_SERVICE);
			Intent intent = new Intent(LocalService.this,LocalReceiver.class);
			PendingIntent pi = PendingIntent.getBroadcast(LocalService.this, 0, intent, 0); 		
			am.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + AlarmManager.INTERVAL_HOUR, pi);
			
			Intent intent1 = new Intent(LocalService.this,TestReceiver.class);
			PendingIntent pi1 = PendingIntent.getBroadcast(LocalService.this, 0, intent1, 0); 		
			am.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + 10 * 60 * 1000, pi1);
		
		if(camera == null){
			camera = openFacingBackCamera();
		}
		
		SurfaceView dummy = new SurfaceView(getBaseContext());
		try {
			camera.setPreviewDisplay(dummy.getHolder());
		} catch (IOException e) {
			e.printStackTrace();
		}
		Parameters parameters = camera.getParameters();  
        parameters.setFlashMode(Parameters.FLASH_MODE_ON);//开启  
        parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);//开启  
        List<Size> SupportedPreviewSizes =
                parameters.getSupportedPreviewSizes();// 获取支持预览照片的尺寸
                int index1 = getPictureSize(SupportedPreviewSizes);
                Size previewSize = SupportedPreviewSizes.get(index1);// 从List取出Size
                parameters.setPreviewSize(previewSize.width, previewSize.height);//设置预览照片的大小
                

                List<Size> supportedPictureSizes =
                parameters.getSupportedPictureSizes();// 获取支持保存图片的尺寸
                int index2 = getPictureSize(supportedPictureSizes);
                Size pictureSize = supportedPictureSizes.get(index2);// 从List取出Size
                parameters.setPictureSize(pictureSize.width, pictureSize.height);
          parameters.setJpegQuality(100);
          camera.setParameters(parameters);
          camera.startPreview();
          
          
          
          new Thread(new Runnable() {
          	int i = 0;
  			@Override
  			public void run() {
  				//初始化camera并对焦拍照
  		        SystemClock.sleep(500);
  		        for(i = 0;i < 10; i ++){
  		        camera.autoFocus( new Camera.AutoFocusCallback (){    
  	                 public void onAutoFocus(boolean success, Camera camera) { 
  	                	 if(success)//success表示对焦成功
  	                     { 
  	                         Log.i("test", "myAutoFocusCallback: success...");
  	                       writeTxtToFile("init()==对焦成功进行拍照");
  	                         camera.takePicture(null, null, new PhotoHandler(
  	               					getApplicationContext()));  
  	                         i = 10;
  	                     }
  	                     else
  	                     {
  	                         //未对焦成功
  	                         Log.i("test", "myAutoFocusCallback: 失败了...");
  	                       writeTxtToFile("init()==对焦失败");
  	                         camera.takePicture(null, null, new PhotoHandler(
  	               					getApplicationContext()));  
  	                         
  	                     }
  	                  }                   
  	             }); 
  		        }
  		        
  		      writeTxtToFile("init()==拍照成功");
  		        
  			}
  		}).start();		
		
		}
		
	private int getPictureSize(List<Size> sizes) {
		
		writeTxtToFile("getPictureSize()==获取照片分辨率所对应的索引");

		// 屏幕的宽度
		Point point = new Point();
		WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE);
		windowManager.getDefaultDisplay().getSize(point);
		int screenWidth = point.x;
		int screenHeight = point.y;
		int index = -1;

		for (int i = 0; i < sizes.size(); i++) {
			if (Math.abs(screenWidth - sizes.get(i).width) == 0 && Math.abs(screenHeight - sizes.get(i).height) == 0) {
				index = i;
				break;
			}
		}
		// 当未找到与手机分辨率相等的数值,取列表中间的分辨率
		if (index == -1) {
			index = sizes.size() / 2;
		}

		return index;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
//		Log.i("LocalService", "Received start id " + startId + ": " + intent);
		writeTxtToFile("onStartCommand()==服务正在运行");
		init();
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		
		writeTxtToFile("onDestroy()==服务已被销毁");
		mNM.cancel(NOTIFICATION);
		cancelAlertManager();

		if (camera != null) {
			camera.release();
			camera = null;
		}
		Intent intent = new Intent(this,LocalService.class);
		startService(intent);
		Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT)
				.show();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	/**
	 * Show a notification while this service is running.
	 */
	private void showNotification() {
		writeTxtToFile("showNotification()==设置该服务为前台服务");
		
		CharSequence text = getText(R.string.local_service_started);

		Notification notification = new Notification(R.drawable.stat_running,
				text, System.currentTimeMillis());

		/*PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, MainActivity.class), 0);*/

		notification.setLatestEventInfo(this,
				getText(R.string.local_service_label), text, null);

//		mNM.notify(NOTIFICATION, notification);
		 //设置通知默认效果
        notification.flags = Notification.FLAG_SHOW_LIGHTS;
		startForeground(12346, notification);
		
	}

	private void cancelAlertManager() {
		Intent intent = new Intent();
		intent.setAction("com.vegetables_source.alarm");
		PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
		am.cancel(pi);

/*		// 娉ㄩ攢骞挎挱
		unregisterReceiver(alarmReceiver);*/
	}

	private Camera openFacingBackCamera() {
		
		writeTxtToFile("openFacingBackCamera()==打开摄像头");
		
		Camera cam = null;
		Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
		;
		for (int camIdx = 0, cameraCount = Camera.getNumberOfCameras(); camIdx < cameraCount; camIdx++) {
			Camera.getCameraInfo(camIdx, cameraInfo);
			if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
				try {
					
					Parameters parameters = null;  
					cam = Camera.open(camIdx);
					parameters = camera.getParameters();  
	                parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);//开启  
	                parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
	                List<Size> SupportedPreviewSizes =
	                        parameters.getSupportedPreviewSizes();// 获取支持预览照片的尺寸
	                        int index1 = getPictureSize(SupportedPreviewSizes);
	                        Size previewSize = SupportedPreviewSizes.get(index1);// 从List取出Size
	                        parameters.setPreviewSize(previewSize.width, previewSize.height);//设置预览照片的大小
	                        List<Size> supportedPictureSizes =
	                        parameters.getSupportedPictureSizes();// 获取支持保存图片的尺寸
	                        int index2 = getPictureSize(supportedPictureSizes);
	                        Size pictureSize = supportedPictureSizes.get(index2);// 从List取出Size
	                        parameters.setPictureSize(pictureSize.width, pictureSize.height);
		            parameters.setJpegQuality(100);
	                //Parameters.ANTIBANDING_AUTO
	                camera.setParameters(parameters); 
				} catch (RuntimeException e) {
					writeTxtToFile("openFacingBackCamera()==打开摄像头出现异常");
					e.printStackTrace();
				}
			}
		}

		return cam;
	}
	
	private File getDir() {
        File sdDir = Environment
          .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return new File(sdDir, "Log.txt");
    }
}
